<template>
	<view class="container">
		<public-module leftIcon="arrow-left" title="资料分析训练" />
		
		<!-- 训练配置区域 -->
		<view v-if="!isTraining && !showResult" class="config-section">
			<view class="config-title">训练设置</view>
			
			<!-- 题目类型选择 -->
			<view class="question-type-section">
				<view class="section-title">题目类型</view>
				<view class="type-grid">
					<view 
						v-for="(type, index) in questionTypes" 
						:key="index"
						class="type-item"
						:class="{ active: selectedTypes.includes(type.key) }"
						@click="toggleQuestionType(type.key)"
					>
						{{ type.name }}
					</view>
				</view>
			</view>

			<!-- 竞速模式选择 -->
			<view class="mode-section">
				<view class="section-title">竞速模式</view>
				<view class="mode-options">
					<view 
						v-for="(mode, index) in competitionModes" 
						:key="index"
						class="mode-option"
						:class="{ active: selectedMode === mode.key }"
						@click="selectMode(mode.key)"
					>
						<u-icon name="checkmark" v-if="selectedMode === mode.key" color="#4CAF50" size="16"></u-icon>
						{{ mode.name }}
					</view>
				</view>
			</view>

			<!-- 开始训练按钮 -->
			<view class="start-button-container">
				<u-button 
					type="primary" 
					:disabled="selectedTypes.length === 0"
					@click="startTraining"
					class="start-button"
				>
					开始练习
				</u-button>
			</view>
		</view>

		<!-- 训练区域 -->
		<view v-if="isTraining" class="training-section">
			<!-- 进度显示 -->
			<view class="progress-info">
				<text class="progress-text">{{ currentQuestion + 1 }} / {{ totalQuestions }}</text>
				<text class="timer" v-if="selectedMode === 'timed'">{{ formatTime(remainingTime) }}</text>
			</view>

			<!-- 题目文字 -->
			<view class="question-text">
				{{ currentQuestionData.question }}
			</view>

			<!-- 选择题选项 -->
			<view v-if="currentQuestionData.options" class="options-section">
				<view 
					v-for="(option, index) in currentQuestionData.options" 
					:key="index"
					class="option-item"
					:class="{ selected: selectedOption === option.label }"
					@click="selectOption(option.label, option.value)"
				>
					<view class="option-label">{{ option.label }}</view>
					<view class="option-value">{{ option.value }}</view>
				</view>
			</view>

			<!-- 直接输入答案 -->
			<view v-else class="answer-input-section">
				<u-input 
					v-model="userAnswer" 
					placeholder="请输入答案"
					type="number"
					class="answer-input"
					@confirm="submitAnswer"
				></u-input>
				<u-button 
					type="primary" 
					@click="submitAnswer"
					:disabled="!userAnswer.trim()"
					class="submit-button"
				>
					提交
				</u-button>
			</view>

			<!-- 选择题提交按钮 -->
			<view v-if="currentQuestionData.options" class="submit-section">
				<u-button 
					type="primary" 
					@click="submitAnswer"
					:disabled="!selectedOption"
					class="submit-button-full"
				>
					提交答案
				</u-button>
			</view>
		</view>

		<!-- 结果总结区域 -->
		<view v-if="showResult" class="result-section" style="padding-top: 16px;">
			<view class="result-header">
				<text class="result-title">训练完成</text>
			</view>
			
			<view class="result-stats">
				<view class="stat-item">
					<text class="stat-label">正确率</text>
					<text class="stat-value">{{ accuracy }}%</text>
				</view>
				<view class="stat-item">
					<text class="stat-label">用时</text>
					<text class="stat-value">{{ formatTime(totalTime) }}</text>
				</view>
				<view class="stat-item">
					<text class="stat-label">答对题数</text>
					<text class="stat-value">{{ correctCount }}/{{ totalQuestions }}</text>
				</view>
			</view>

			<!-- 错题回顾 -->
			<view v-if="wrongQuestions.length > 0" class="wrong-questions">
				<view class="wrong-title">错题回顾</view>
				<view v-for="(item, index) in wrongQuestions" :key="index" class="wrong-item">
					<view class="wrong-question">{{ item.question }}</view>
					<view class="wrong-answer">
						<text>正确答案：{{ item.correctAnswer }}</text>
						<text>您的答案：{{ item.userAnswer }}</text>
					</view>
				</view>
			</view>

			<!-- 重新开始按钮 -->
			<view class="restart-button-container">
				<u-button type="primary" @click="resetTraining" class="restart-button">
					重新开始
				</u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import { mapState, mapMutations } from 'vuex';
	
	export default {
		data() {
			return {
				// 题目类型
				questionTypes: [
					{ key: 'base_period', name: '基期' },
					{ key: 'current_period', name: '现期' },
					{ key: 'growth_amount', name: '增长量' },
					{ key: 'growth_rate', name: '增长率' },
					{ key: 'growth_contribution', name: '增长贡献率' },
					{ key: 'pulling_growth', name: '拉动增长率' },
					{ key: 'two_period_proportion', name: '两期比重差' },
					{ key: 'annual_growth', name: '年均增长率' },
					{ key: 'average_growth', name: '平均增长率' },
					{ key: 'random', name: '随机题型' }
				],
				
				// 竞速模式
				competitionModes: [
					{ key: 'practice', name: '竞速模式（10题一组）' }
				],
				
				// 选中的题目类型
				selectedTypes: ['base_period'],
				
				// 选中的模式
				selectedMode: 'practice',
				
				// 训练状态
				isTraining: false,
				showResult: false,
				
				// 题目相关
				questions: [],
				currentQuestion: 0,
				totalQuestions: 10,
				currentQuestionData: {},
				userAnswer: '',
				
				// 选中的选项
				selectedOption: '',
				selectedValue: null,
				
				// 计时相关
				timer: null,
				startTime: 0,
				totalTime: 0,
				remainingTime: 300, // 5分钟
				
				// 结果统计
				correctCount: 0,
				wrongQuestions: [],
				answers: []
			}
		},
		
		computed: {
			...mapState(['user', 'loginSuccess']),
			
			accuracy() {
				return this.totalQuestions > 0 ? Math.round((this.correctCount / this.totalQuestions) * 100) : 0;
			}
		},
		
		methods: {
			...mapMutations([]),
			
			// 切换题目类型选择（单选模式）
			toggleQuestionType(type) {
				// 单选模式，每次只能选择一个类型
				this.selectedTypes = [type];
			},
			
			// 选择竞速模式
			selectMode(mode) {
				this.selectedMode = mode;
			},
			
			// 选择选项
			selectOption(label, value) {
				this.selectedOption = label;
				this.selectedValue = value;
			},
			
			// 开始训练
			startTraining() {
				// 检查登录状态
				if (!this.user?.userId) {
					// 静默登录机制，直接跳转到首页
					uni.reLaunch({
						url: '/pages/index/index'
					});
					return;
				}
				
				if (this.selectedTypes.length === 0) {
					uni.showToast({
						title: '请选择题目类型',
						icon: 'none'
					});
					return;
				}
				
				this.isTraining = true;
				this.showResult = false;
				this.currentQuestion = 0;
				this.correctCount = 0;
				this.wrongQuestions = [];
				this.answers = [];
				this.startTime = Date.now();
				
				// 生成题目
				this.generateQuestions();
				this.loadCurrentQuestion();
				
				// 如果是限时模式，开始计时
				if (this.selectedMode === 'timed') {
					this.startTimer();
				}
			},
			
			// 生成题目
			generateQuestions() {
				this.questions = [];
				for (let i = 0; i < this.totalQuestions; i++) {
					const question = this.generateSingleQuestion();
					this.questions.push(question);
				}
			},
			
			// 生成单个题目
			generateSingleQuestion() {
				const types = this.selectedTypes.includes('random') 
					? this.questionTypes.filter(t => t.key !== 'random').map(t => t.key)
					: this.selectedTypes;
				
				const randomType = types[Math.floor(Math.random() * types.length)];
				
				// 根据题目类型生成不同的题目
				switch (randomType) {
					case 'base_period':
						return this.generateBasePeriodQuestion();
					case 'current_period':
						return this.generateCurrentPeriodQuestion();
					case 'growth_amount':
						return this.generateGrowthAmountQuestion();
					case 'growth_rate':
						return this.generateGrowthRateQuestion();
					case 'growth_contribution':
						return this.generateGrowthContributionQuestion();
					case 'pulling_growth':
						return this.generatePullingGrowthQuestion();
					case 'two_period_proportion':
						return this.generateTwoPeriodProportionQuestion();
					case 'annual_growth':
						return this.generateAnnualGrowthQuestion();
					case 'average_growth':
						return this.generateAverageGrowthQuestion();
					default:
						return this.generateBasePeriodQuestion();
				}
			},
			
			// 生成增长量题目
			generateGrowthAmountQuestion() {
				// 支持正负增长量，更符合实际经济情况
				const basePeriodValue = Math.floor(Math.random() * 4000) + 2000; // 2000-6000
				const isNegativeGrowth = Math.random() < 0.3; // 30%概率为负增长
				let growthRate;
				
				if (isNegativeGrowth) {
					// 负增长：-15%到-2%
					growthRate = -(Math.random() * 13 + 2) / 100;
				} else {
					// 正增长：2%到18%
					growthRate = (Math.random() * 16 + 2) / 100;
				}
				
				const currentValue = Math.round(basePeriodValue * (1 + growthRate));
				const growthAmount = currentValue - basePeriodValue;
				
				const sectors = ['第一产业', '第二产业', '第三产业', '民营经济', '国有经济'];
				const sector = sectors[Math.floor(Math.random() * sectors.length)];
				
				const options = this.generateAnswerOptions(growthAmount);
				
				// 根据增长量正负调整问题描述
				const changeWord = growthAmount >= 0 ? '增长量' : '下降量';
				const questionText = `2023年江苏省${sector}增加值为${currentValue}亿元，2022年为${basePeriodValue}亿元。\n\n2023年江苏省${sector}增加值的${changeWord}为多少亿元？`;
				
				return {
					type: 'growth_amount',
					question: questionText,
					correctAnswer: growthAmount,
					options: options,
					currentValue,
					basePeriodValue,
					growthRate: growthRate * 100 // 转为百分比显示
				};
			},
			
			// 生成基期量/基期数值题目（按照图片样式）
			generateBasePeriodQuestion() {
				// 生成现期数值（三位数到四位数）
				const currentValue = Math.floor(Math.random() * 9000) + 1000;
				// 生成增长率（小增长率规范：0.2%-4.9%，30%概率为负）
				const growthRate = (Math.random() * 4.7 + 0.2).toFixed(1);
				const isNegative = Math.random() < 0.3;
				const finalGrowthRate = isNegative ? -parseFloat(growthRate) : parseFloat(growthRate);
				
				// 计算基期值 = 现期值 / (1 + 增长率)
				const basePeriodValue = Math.round(currentValue / (1 + finalGrowthRate / 100));
				
				// 生成年份和地区
				const currentYear = 2023;
				const baseYear = 2022;
				const areas = ['江苏省', 'G市', 'S市', 'N市', '某地区'];
				const industries = ['智能机器人产业', '新能源产业', '电子信息产业', '生物医药产业', '高端装备制造业'];
				const area = areas[Math.floor(Math.random() * areas.length)];
				const industry = industries[Math.floor(Math.random() * industries.length)];
				
				// 生成答案选项（四个选项）
				const options = this.generateAnswerOptions(basePeriodValue);
				
				return {
					type: 'base_period',
					question: `${currentYear}年前三季度，${area}${industry}实现营业收入${currentValue}亿元，同比增长${finalGrowthRate}%。\n\n${baseYear}年前三季度，${area}${industry}实现营业收入多少亿元？`,
					correctAnswer: basePeriodValue,
					options: options,
					currentValue,
					growthRate: finalGrowthRate
				};
			},
			
			// 生成现期量/现期数值题目
			generateCurrentPeriodQuestion() {
				const basePeriodValue = Math.floor(Math.random() * 9000) + 1000;
				const growthRate = (Math.random() * 4.7 + 0.2).toFixed(1);
				const isNegative = Math.random() < 0.3;
				const finalGrowthRate = isNegative ? -parseFloat(growthRate) : parseFloat(growthRate);
				const currentValue = Math.round(basePeriodValue * (1 + finalGrowthRate / 100));
						
				const areas = ['江苏省', 'G市', 'S市', 'N市', '某地区'];
				const industries = ['智能机器人产业', '新能源产业', '电子信息产业'];
				const area = areas[Math.floor(Math.random() * areas.length)];
				const industry = industries[Math.floor(Math.random() * industries.length)];
						
				const options = this.generateAnswerOptions(currentValue);
						
				return {
					type: 'current_period',
					question: `2022年前三季度，${area}${industry}实现营业收入${basePeriodValue}亿元，2023年前三季度同比增长${finalGrowthRate}%。\n\n2023年前三季度，${area}${industry}实现营业收入多少亿元？`,
					correctAnswer: currentValue,
					options: options,
					basePeriodValue,
					growthRate: finalGrowthRate
				};
			},
			
			// 生成增长率题目
			generateGrowthRateQuestion() {
				// 支持正负增长率，更符合实际经济情况
				const basePeriodValue = Math.floor(Math.random() * 4000) + 2000;
				const isNegativeGrowth = Math.random() < 0.25; // 25%概率为负增长
				let growthRate;
				
				if (isNegativeGrowth) {
					// 负增长率：-12%到-1%
					growthRate = -(Math.random() * 11 + 1);
				} else {
					// 正增长率：1%到15%
					growthRate = Math.random() * 14 + 1;
				}
				
				const currentValue = Math.round(basePeriodValue * (1 + growthRate / 100));
				
				const areas = ['江苏省', '苏州市', '南京市', '无锡市'];
				const industries = ['制造业', '服务业', '建筑业', '金融业'];
				const area = areas[Math.floor(Math.random() * areas.length)];
				const industry = industries[Math.floor(Math.random() * industries.length)];
				
				const options = this.generateGrowthRateOptions(parseFloat(growthRate.toFixed(1)));
				
				// 根据增长率正负调整问题描述
				const changeWord = growthRate >= 0 ? '增长' : '下降';
				const rateValue = Math.abs(growthRate).toFixed(1);
				const questionText = `2023年${area}${industry}增加值为${currentValue}亿元，2022年为${basePeriodValue}亿元。\n\n2023年${area}${industry}增加值同比${changeWord}了多少？`;
				
				return {
					type: 'growth_rate',
					question: questionText,
					correctAnswer: parseFloat(growthRate.toFixed(1)),
					options: options,
					currentValue,
					basePeriodValue
				};
			},

			// 生成增长贡献率题目
			generateGrowthContributionQuestion() {
				const totalGrowth = (Math.random() * 10 + 5).toFixed(1);
				const partGrowth = (Math.random() * 3 + 1).toFixed(1);
				const contributionRate = (partGrowth / totalGrowth * 100).toFixed(1);
				
				const areas = ['江苏省', '苏州市', '南京市'];
				const area = areas[Math.floor(Math.random() * areas.length)];
				const sectors = ['第一产业', '第二产业', '第三产业'];
				const sector = sectors[Math.floor(Math.random() * sectors.length)];
				
				const options = this.generateGrowthRateOptions(parseFloat(contributionRate));
				
				return {
					type: 'growth_contribution',
					question: `2023年${area}地区生产总值增长${totalGrowth}%，其中${sector}增长${partGrowth}个百分点。\n\n${sector}对${area}地区生产总值增长的贡献率为多少？`,
					correctAnswer: parseFloat(contributionRate),
					options: options,
					totalGrowth: parseFloat(totalGrowth),
					partGrowth: parseFloat(partGrowth)
				};
			},

			// 生成拉动增长率题目
			generatePullingGrowthQuestion() {
				const totalValue = Math.floor(Math.random() * 10000) + 5000;
				const partValue = Math.floor(Math.random() * 3000) + 1000;
				const partGrowthRate = (Math.random() * 8 + 2).toFixed(1);
				const pullingGrowth = (partValue / totalValue * parseFloat(partGrowthRate)).toFixed(2);
				
				const areas = ['江苏省', '苏州市', '南京市', '无锡市'];
				const area = areas[Math.floor(Math.random() * areas.length)];
				const sectors = ['工业', '服务业', '农业'];
				const sector = sectors[Math.floor(Math.random() * sectors.length)];
				
				const options = this.generateGrowthRateOptions(parseFloat(pullingGrowth));
				
				return {
					type: 'pulling_growth',
					question: `2023年${area}地区生产总值为${totalValue}亿元，${sector}增加值为${partValue}亿元，同比增长${partGrowthRate}%。\n\n${sector}对${area}地区生产总值增长的拉动作用为多少个百分点？`,
					correctAnswer: parseFloat(pullingGrowth),
					options: options,
					totalValue,
					partValue,
					partGrowthRate: parseFloat(partGrowthRate)
				};
			},

			// 生成两期比重差题目
			generateTwoPeriodProportionQuestion() {
				const totalCurrent = Math.floor(Math.random() * 10000) + 5000;
				const partCurrent = Math.floor(Math.random() * 3000) + 1000;
				const totalGrowthRate = (Math.random() * 6 + 4).toFixed(1);
				const partGrowthRate = (Math.random() * 8 + 2).toFixed(1);
				
				const proportionCurrent = (partCurrent / totalCurrent * 100).toFixed(2);
				const totalBase = totalCurrent / (1 + parseFloat(totalGrowthRate) / 100);
				const partBase = partCurrent / (1 + parseFloat(partGrowthRate) / 100);
				const proportionBase = (partBase / totalBase * 100).toFixed(2);
				const proportionDiff = (parseFloat(proportionCurrent) - parseFloat(proportionBase)).toFixed(2);
				
				const areas = ['江苏省', '苏州市', '南京市'];
				const area = areas[Math.floor(Math.random() * areas.length)];
				const sectors = ['第三产业', '制造业', '服务业'];
				const sector = sectors[Math.floor(Math.random() * sectors.length)];
				
				const options = this.generateGrowthRateOptions(parseFloat(proportionDiff));
				
				return {
					type: 'two_period_proportion',
					question: `2023年${area}地区生产总值为${totalCurrent}亿元，同比增长${totalGrowthRate}%；${sector}增加值为${partCurrent}亿元，同比增长${partGrowthRate}%。\n\n2023年${sector}增加值占地区生产总值的比重比2022年提高或下降了多少个百分点？`,
					correctAnswer: parseFloat(proportionDiff),
					options: options,
					totalCurrent,
					partCurrent,
					totalGrowthRate: parseFloat(totalGrowthRate),
					partGrowthRate: parseFloat(partGrowthRate)
				};
			},

			// 生成年均增长率题目
			generateAnnualGrowthQuestion() {
				const initialValue = Math.floor(Math.random() * 3000) + 1000;
				const years = Math.floor(Math.random() * 3) + 3;
				const annualRate = (Math.random() * 8 + 2).toFixed(1);
				const finalValue = Math.round(initialValue * Math.pow(1 + parseFloat(annualRate) / 100, years));
				
				const startYear = 2018 + Math.floor(Math.random() * 3);
				const endYear = startYear + years;
				const areas = ['江苏省', '苏州市', '南京市', '无锡市'];
				const area = areas[Math.floor(Math.random() * areas.length)];
				const indicators = ['GDP', '工业总产值', '固定资产投资', '社会消费品零售总额'];
				const indicator = indicators[Math.floor(Math.random() * indicators.length)];
				
				const options = this.generateGrowthRateOptions(parseFloat(annualRate));
				
				return {
					type: 'annual_growth',
					question: `${startYear}年${area}${indicator}为${initialValue}亿元，${endYear}年为${finalValue}亿元。\n\n${startYear}-${endYear}年${area}${indicator}的年均增长率约为多少？`,
					correctAnswer: parseFloat(annualRate),
					options: options,
					initialValue,
					finalValue,
					years
				};
			},

			// 生成平均增长率题目
			generateAverageGrowthQuestion() {
				const values = [];
				const years = [];
				const numYears = 3 + Math.floor(Math.random() * 2);
				
				for (let i = 0; i < numYears; i++) {
					years.push(2020 + i);
					values.push(Math.floor(Math.random() * 2000) + 1000 + i * 200);
				}
				
				let totalGrowthRate = 0;
				for (let i = 1; i < values.length; i++) {
					totalGrowthRate += (values[i] - values[i-1]) / values[i-1] * 100;
				}
				const averageGrowthRate = (totalGrowthRate / (values.length - 1)).toFixed(1);
				
				const areas = ['江苏省', '苏州市', '南京市'];
				const area = areas[Math.floor(Math.random() * areas.length)];
				const indicators = ['规模以上工业增加值', '固定资产投资', '社会消费品零售总额'];
				const indicator = indicators[Math.floor(Math.random() * indicators.length)];
				
				let questionText = `${area}${indicator}情况如下：\n`;
				for (let i = 0; i < years.length; i++) {
					questionText += `${years[i]}年：${values[i]}亿元\n`;
				}
				questionText += `\n${years[0]}-${years[years.length-1]}年${area}${indicator}的平均增长率约为多少？`;
				
				const options = this.generateGrowthRateOptions(parseFloat(averageGrowthRate));
				
				return {
					type: 'average_growth',
					question: questionText,
					correctAnswer: parseFloat(averageGrowthRate),
					options: options,
					values,
					years
				};
			},
			
			// 加载当前题目
			loadCurrentQuestion() {
				if (this.currentQuestion < this.questions.length) {
					this.currentQuestionData = this.questions[this.currentQuestion];
					this.userAnswer = '';
					this.selectedOption = '';
					this.selectedValue = null;
				}
			},
			
			// 提交答案
			submitAnswer() {
				let userAnswerValue;
				
				// 检查是选择题还是填空题
				if (this.currentQuestionData.options) {
					// 选择题
					if (!this.selectedOption) {
						uni.showToast({
							title: '请选择答案',
							icon: 'none'
						});
						return;
					}
					userAnswerValue = this.selectedValue;
				} else {
					// 填空题
					if (!this.userAnswer.trim()) {
						uni.showToast({
							title: '请输入答案',
							icon: 'none'
						});
						return;
					}
					userAnswerValue = parseFloat(this.userAnswer);
				}
				
				const correctAnswer = this.currentQuestionData.correctAnswer;
				const isCorrect = Math.abs(userAnswerValue - correctAnswer) <= 0.1;
				
				this.answers.push({
					question: this.currentQuestionData.question,
					userAnswer: userAnswerValue,
					correctAnswer: correctAnswer,
					isCorrect: isCorrect
				});
				
				if (isCorrect) {
					this.correctCount++;
				} else {
					this.wrongQuestions.push({
						question: this.currentQuestionData.question,
						userAnswer: userAnswerValue,
						correctAnswer: correctAnswer
					});
				}
				
				this.currentQuestion++;
				
				if (this.currentQuestion >= this.totalQuestions) {
					this.finishTraining();
				} else {
					this.loadCurrentQuestion();
				}
			},
			
			// 完成训练
			finishTraining() {
				this.isTraining = false;
				this.showResult = true;
				this.totalTime = Date.now() - this.startTime;
				
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = null;
				}
				
				// 保存训练记录
				this.saveTrainingRecord();
			},
			
			// 保存训练记录
			async saveTrainingRecord() {
				// 这里添加保存记录到服务器的逻辑
				console.log('保存训练记录:', {
					type: 'data_analysis',
					selectedTypes: this.selectedTypes,
					mode: this.selectedMode,
					correctCount: this.correctCount,
					totalQuestions: this.totalQuestions,
					accuracy: this.accuracy,
					totalTime: this.totalTime,
					answers: this.answers
				});
			},
			
			// 重置训练
			resetTraining() {
				this.isTraining = false;
				this.showResult = false;
				this.currentQuestion = 0;
				this.userAnswer = '';
				this.selectedOption = '';
				this.selectedValue = null;
				this.correctCount = 0;
				this.wrongQuestions = [];
				this.answers = [];
				
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = null;
				}
			},
			
			// 开始计时器
			startTimer() {
				this.timer = setInterval(() => {
					this.remainingTime--;
					if (this.remainingTime <= 0) {
						this.finishTraining();
					}
				}, 1000);
			},
			
			// 格式化时间
			formatTime(milliseconds) {
				const seconds = Math.floor(milliseconds / 1000);
				const minutes = Math.floor(seconds / 60);
				const remainingSeconds = seconds % 60;
				return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
			},
			
			// 生成答案选项（数值类）
			generateAnswerOptions(correctAnswer) {
				const options = [correctAnswer];
				let attempts = 0;
				const maxAttempts = 50; // 防止无限循环
				
				// 生成三个干扰选项，偏差范围从-10%到15%
				while (options.length < 4 && attempts < maxAttempts) {
					attempts++;
					const variance = Math.random() * 0.25 - 0.1; // -10%到15%范围的偏差
					let wrongAnswer;
					
					// 针对不同数值范围的特殊处理
					if (Math.abs(correctAnswer) < 10) {
						// 对于小数值（包括负数、零、小正数），使用加减法
						wrongAnswer = Math.round(correctAnswer + (Math.random() - 0.5) * 50);
					} else {
						// 对于较大数值，使用百分比偏差
						wrongAnswer = Math.round(correctAnswer * (1 + variance));
					}
					
					// 移除过于严格的正数限制，允许负数选项
					if (!options.includes(wrongAnswer)) {
						options.push(wrongAnswer);
					}
				}
				
				// 如果仍然没有生成足够的选项，手动补充
				while (options.length < 4) {
					const baseValue = Math.abs(correctAnswer) < 10 ? 20 : Math.abs(correctAnswer);
					const randomOption = Math.round(correctAnswer + (Math.random() - 0.5) * baseValue * 0.8);
					if (!options.includes(randomOption)) {
						options.push(randomOption);
					}
				}
				
				// 打乱选项顺序
				for (let i = options.length - 1; i > 0; i--) {
					const j = Math.floor(Math.random() * (i + 1));
					[options[i], options[j]] = [options[j], options[i]];
				}
				
				return options.map((option, index) => ({
					label: String.fromCharCode(65 + index), // A, B, C, D
					value: option
				}));
			},
			
			// 生成增长率类选项（百分比）
			generateGrowthRateOptions(correctAnswer) {
				const options = [correctAnswer];
				let attempts = 0;
				const maxAttempts = 50; // 防止无限循环
				
				// 生成三个干扰选项，偏差范围从-10%到15%
				while (options.length < 4 && attempts < maxAttempts) {
					attempts++;
					const variance = Math.random() * 0.25 - 0.1; // -10%到15%范围的偏差
					let wrongAnswer;
					
					// 针对百分比数据的特殊处理（支持正负值）
					if (Math.abs(correctAnswer) < 1) {
						// 当正确答案接近0时，生成小范围的正负数
						wrongAnswer = parseFloat(((Math.random() - 0.5) * 4).toFixed(1));
					} else {
						// 常规情况，支持负增长率
						wrongAnswer = parseFloat((correctAnswer * (1 + variance)).toFixed(1));
					}
					
					// 移除过于严格的正数限制，允许负数选项
					if (!options.includes(wrongAnswer)) {
						options.push(wrongAnswer);
					}
				}
				
				// 如果仍然没有生成足够的选项，手动补充
				while (options.length < 4) {
					const baseValue = Math.abs(correctAnswer) < 1 ? 2 : Math.abs(correctAnswer);
					const randomOption = parseFloat((correctAnswer + (Math.random() - 0.5) * baseValue * 0.8).toFixed(1));
					if (!options.includes(randomOption)) {
						options.push(randomOption);
					}
				}
				
				// 打乱选项顺序
				for (let i = options.length - 1; i > 0; i--) {
					const j = Math.floor(Math.random() * (i + 1));
					[options[i], options[j]] = [options[j], options[i]];
				}
				
				return options.map((option, index) => ({
					label: String.fromCharCode(65 + index), // A, B, C, D
					value: option
				}));
			},
			

		},
		
		beforeDestroy() {
			if (this.timer) {
				clearInterval(this.timer);
			}
		}
	}
</script>

<style scoped>
	.container {
		min-height: 100vh;
		background-color: #f8f8f8;
	}
	
	.config-section {
		padding: 16px;
		background-color: #ffffff;
		margin: 8px;
		border-radius: 8px;
	}
	
	.config-title {
		font-size: 18px;
		font-weight: bold;
		color: #333333;
		margin-bottom: 16px;
	}
	
	.question-type-section {
		margin-bottom: 24px;
	}
	
	.section-title {
		font-size: 16px;
		font-weight: 500;
		color: #333333;
		margin-bottom: 12px;
	}
	
	.type-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 10px;
		overflow-x: auto;
	}
	
	.type-item {
		padding: 12px 16px;
		background-color: #f5f5f5;
		border: 2px solid transparent;
		border-radius: 8px;
		text-align: center;
		font-size: 14px;
		color: #666666;
		transition: all 0.3s ease;
		min-width: 50px;
		white-space: nowrap;
		flex-shrink: 0;
	}
	
	.type-item.active {
		background-color: #e3f2fd;
		border-color: #2196f3;
		color: #2196f3;
	}
	
	.mode-section {
		margin-bottom: 24px;
	}
	
	.mode-options {
		display: flex;
		flex-direction: column;
		gap: 8px;
	}
	
	.mode-option {
		display: flex;
		align-items: center;
		gap: 8px;
		padding: 12px 16px;
		background-color: #f5f5f5;
		border-radius: 8px;
		font-size: 14px;
		color: #666666;
		transition: all 0.3s ease;
	}
	
	.mode-option.active {
		background-color: #e8f5e8;
		color: #4CAF50;
	}
	
	.start-button-container {
		display: flex;
		justify-content: center;
		margin-top: 16px;
	}
	
	.start-button {
		width: 200px;
		margin: 10px auto 0;
		min-width: 50px;
	}
	
	.training-section {
		padding: 16px;
		background-color: #ffffff;
		margin: 8px;
		border-radius: 8px;
	}
	
	.progress-info {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16px;
		padding: 8px 0;
		border-bottom: 1px solid #eee;
	}
	
	.progress-text {
		font-size: 16px;
		font-weight: 500;
		color: #333333;
	}
	
	.timer {
		font-size: 16px;
		font-weight: 500;
		color: #ff9800;
	}
	
	.question-text {
		font-size: 16px;
		line-height: 1.6;
		color: #333333;
		margin-bottom: 16px;
		padding: 12px;
		background-color: #f9f9f9;
		border-radius: 8px;
	}
	
	.answer-input-section {
		display: flex;
		gap: 12px;
		align-items: center;
	}
	
	.answer-input {
		flex: 1;
	}
	
	.submit-button {
		width: 80px;
		flex-shrink: 0;
	}
	
	.options-section {
		margin-bottom: 16px;
	}
	
	.option-item {
		display: flex;
		align-items: center;
		padding: 12px 16px;
		margin-bottom: 8px;
		background-color: #f5f5f5;
		border: 2px solid transparent;
		border-radius: 8px;
		transition: all 0.3s ease;
		cursor: pointer;
	}
	
	.option-item.selected {
		background-color: #e3f2fd;
		border-color: #2196f3;
	}
	
	.option-label {
		width: 30px;
		height: 30px;
		border-radius: 50%;
		background-color: #ffffff;
		border: 2px solid #ddd;
		display: flex;
		align-items: center;
		justify-content: center;
		font-weight: bold;
		color: #666;
		margin-right: 12px;
		flex-shrink: 0;
	}
	
	.option-item.selected .option-label {
		background-color: #2196f3;
		border-color: #2196f3;
		color: #ffffff;
	}
	
	.option-value {
		flex: 1;
		font-size: 16px;
		color: #333333;
	}
	
	.submit-section {
		margin-top: 16px;
		display: flex;
		justify-content: center;
	}
	
	.submit-button-full {
		width: 200px;
		margin: 10px auto 0;
		min-width: 50px;
	}
	
	.result-section {
		padding: 16px;
		background-color: #ffffff;
		margin: 8px;
		border-radius: 8px;
		padding-top: 16px;
	}
	
	.result-header {
		text-align: center;
		margin-bottom: 20px;
	}
	
	.result-title {
		font-size: 20px;
		font-weight: bold;
		color: #333333;
	}
	
	.result-stats {
		display: flex;
		justify-content: space-around;
		margin-bottom: 20px;
		padding: 16px;
		background-color: #f9f9f9;
		border-radius: 8px;
	}
	
	.stat-item {
		text-align: center;
		flex: 1;
	}
	
	.stat-label {
		display: block;
		font-size: 14px;
		color: #666666;
		margin-bottom: 4px;
	}
	
	.stat-value {
		display: block;
		font-size: 18px;
		font-weight: bold;
		color: #333333;
	}
	
	.wrong-questions {
		margin-bottom: 20px;
	}
	
	.wrong-title {
		font-size: 16px;
		font-weight: 500;
		color: #333333;
		margin-bottom: 12px;
	}
	
	.wrong-item {
		margin-bottom: 12px;
		padding: 12px;
		background-color: #fff3e0;
		border-radius: 8px;
		border-left: 4px solid #ff9800;
	}
	
	.wrong-question {
		font-size: 14px;
		color: #333333;
		margin-bottom: 8px;
	}
	
	.wrong-answer {
		display: flex;
		flex-direction: column;
		gap: 4px;
	}
	
	.wrong-answer text {
		font-size: 12px;
		color: #666666;
	}
	
	.restart-button-container {
		display: flex;
		justify-content: center;
	}
	
	.restart-button {
		width: 200px;
		margin: 10px auto 0;
		min-width: 50px;
	}
</style>